#include "common/log/log.h"
#include "sql/operator/update_operator.h"
#include "storage/record/record.h"
#include "storage/common/table.h"
#include "sql/stmt/update_stmt.h"

RC UpdateOperator::open()
{
  if (children_.size() != 1) {
    LOG_WARN("update operator must has 1 child");
    return RC::INTERNAL;
  }

  Operator *child = children_[0];
  RC rc = child->open();
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to open child operator: %s", strrc(rc));
    return rc;
  }

  Table *table = update_stmt_->table();
  while (RC::SUCCESS == (rc = child->next())) {
    Tuple *tuple = child->current_tuple();
    if (nullptr == tuple) {
      LOG_WARN("failed to get current record: %s", strrc(rc));
      return rc;
    }

    RowTuple *row_tuple = static_cast<RowTuple *>(tuple);
    //debug
    // for(int i=0; i<row_tuple->cell_num(); ++i) {
    //   TupleCell tc;
    //   row_tuple->cell_at(i,tc);
    //   std::stringstream ss;
    //   tc.to_string(ss);
    //   LOG_INFO("tc %s", ss.str().c_str());
    // }
    // LOG_INFO("%s", update_stmt_->attr_name());
    std::vector<UpdateAttr*> *update_attr = update_stmt_->update_attrs();
    rc = table->update_record(nullptr, db_, update_attr, row_tuple->record_ptr());
    if(rc != RC::SUCCESS) {
      LOG_ERROR("table->update_record err");
      return rc;
    }
  }

  if (rc != RC::RECORD_EOF) {
    LOG_WARN("something wrong while iterate operator. rc=%s", strrc(rc));
  }
  return RC::SUCCESS;
}

RC UpdateOperator::next()
{
  return RC::RECORD_EOF;
}

RC UpdateOperator::close()
{
  children_[0]->close();
  return RC::SUCCESS;
}